const assert = require('assert');

module.exports = class extends think.Controller {
  constructor(ctx) {
    super(ctx);
    this.resource = this.getResource(); // 不要求对应物理数据表
    this.id = this.getId();
    assert(think.isFunction(this.model), 'this.model must be a function');
  }

  async __before(action) {
    try {
      this.userInfo = await this.ctx.session('userInfo');
    } catch (err) {
      this.userInfo = {};
    }

    // 非GET请求都必须登陆，部分GET请求要验证身份，需要单独操作
    if (this.ctx.method !== 'GET' && think.isEmpty(this.userInfo)) {
      this.ctx.status = 401;
      return this.ctx.fail(-1, '请登录后操作');
    }
  }

  // 部分API GET请求也必须登陆，此时需要验证TOKEN
  verifyAccessPermission(uid = null) {
    const userInfo = this.userInfo;
    // think.logger.info(userInfo);
    if (think.isEmpty(userInfo)) {
      this.ctx.status = 401;
      return this.ctx.fail(-1, '请登录后操作');
    } else {
      if (!think.isEmpty(uid)) {
        if (uid !== userInfo.id) {
          this.ctx.status = 401;
          return this.ctx.fail(-2, '只允许访问用户自己的资源');
        }
      }
    }

    return true;
  }

  getResource() {
    return this.ctx.controller.split('/').slice(-1)[0];
  }

  getId() {
    const id = this.get('id');
    if (id && (think.isString(id) || think.isNumber(id))) {
      return id;
    }
    const last = this.ctx.path.split('/').slice(-1)[0];
    if (last !== this.resource) {
      return last;
    }
    return '';
  }

  __call() {

  }
};
